# -*- coding: utf-8 -*-

############################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#############################################################################

"""
Decorator functions that count the time and times of function calls

100： 100ms Number of calls within
200： 200ms Number of calls within
300： 300ms Number of calls within
400： 400ms Number of calls within
500： 500ms Number of calls within
1000：1000ms Number of calls within
1001：1000ms Number of calls within
cnt： total call numbers
day： Start date of statistics (2020-10-22)
time：Start date of statistics (20:12:00)
"""

import time
from functools import wraps
import datetime as dt

_g_funcdic = {}


def getcost():
    global _g_funcdic

    r = _g_funcdic
    _g_funcdic = {}
    return r


def cost_count_wraps(func):


    @wraps(func)
    def wraper(*args, **kwargs):
        global _g_funcdic
        start = time.time()
        f = func(*args, **kwargs)
        cost = int((time.time() - start) * 1000)
        dic = {}

        if func.__name__ in _g_funcdic:
            dic = _g_funcdic[func.__name__]



        if 'cnt' in dic:
            dic['cnt'] += 1
        else:
            dic['cnt'] = 1
            dic['day'] = dt.datetime.now().strftime('%F')
            dic['time'] = dt.datetime.now().strftime('%T')
            dic['100'] = 0
            dic['200'] = 0
            dic['300'] = 0
            dic['400'] = 0
            dic['500'] = 0
            dic['1000'] = 0
            dic['1001'] = 0

        if cost <= 100:
            dic['100'] += 1
        elif cost <= 500:
            dic['500'] += 1
        elif cost <= 1000:
            dic['1000'] += 1
        else:
            dic['1001'] += 1

        _g_funcdic[func.__name__] = dic

        return f

    return wraper
